package com.ukefu.webim.web.handler.api.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.Menu;
import com.ukefu.util.UKTools;
import com.ukefu.webim.service.es.OrdersCommentRepository;
import com.ukefu.webim.service.es.WorkOrdersRepository;
import com.ukefu.webim.service.repository.AttachmentRepository;
import com.ukefu.webim.service.repository.DataEventRepository;
import com.ukefu.webim.service.repository.PropertiesEventRepository;
import com.ukefu.webim.util.PropertiesEventUtils;
import com.ukefu.webim.util.RestResult;
import com.ukefu.webim.util.RestResultType;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.model.DataEvent;
import com.ukefu.webim.web.model.OrdersComment;
import com.ukefu.webim.web.model.PropertiesEvent;
import com.ukefu.webim.web.model.WorkOrders;

@RestController
@RequestMapping("/api/workorders/process")
@Api(value = "工单服务", description = "处理工单")
public class ApiWorkOrdersProcessController extends Handler{
	
	@Value("${web.upload-path}")
    private String path;

	@Autowired
	private AttachmentRepository attachementRes;
	
	@Autowired
	private WorkOrdersRepository workOrdersRepository;
	
	@Autowired
	private OrdersCommentRepository ordersCommentRes ;

	@Autowired
	private DataEventRepository dataEventRes ;
	
	@Autowired
	private PropertiesEventRepository propertiesEventRes ;
	
	/**
	 * 回复工单
	 * @param request
	 * @param q	
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping( method = RequestMethod.PUT)
	@Menu(type = "apps" , subtype = "workorders" , access = true)
	@ApiOperation("回复工单")
    public ResponseEntity<RestResult> list(HttpServletRequest request ,@Valid WorkOrders workOrders , @Valid String id ,@Valid OrdersComment comment, @Valid MultipartFile[] files) throws IOException {
		RestResult result = new RestResult(RestResultType.OK) ; 
		if(!StringUtils.isBlank(id)){
			WorkOrders tempWorkOrders = workOrdersRepository.findByIdAndOrgi(id,super.getOrgi(request)) ;
	    	if(tempWorkOrders!=null){
	    		if(comment!=null && !StringUtils.isBlank(comment.getContent()) && Jsoup.parse(comment.getContent()).hasText()){
		    		comment.setId(UKTools.getUUID());
		    		comment.setCreater(super.getUser(request).getId());
		    		comment.setOrgi(super.getOrgi(request));
		    		if(!StringUtils.isBlank(comment.getDataid())){
		    			comment.setDataid(id);
		    		}
		    		comment.setCreatetime(new Date());
		    		ordersCommentRes.save(comment) ;
	    		}
	    		if(!StringUtils.isBlank(workOrders.getAccuser())){
	    			workOrders.setAssigned(true);
	    		}else{
	    			workOrders.setAssigned(false);
	    		}
	    		List<PropertiesEvent> events = PropertiesEventUtils.processPropertiesModify(request, workOrders , tempWorkOrders , "id" , "orgi" , "creater" ,"createtime" , "updatetime") ;	//记录 数据变更 历史
		    	if(events.size()>0){
		    		
		    		workOrders.setUpdatetime(new Date());
		    		workOrders.setContent(tempWorkOrders.getContent());
		    		workOrders.setCreater(tempWorkOrders.getCreater());
		    		workOrders.setCreatetime(tempWorkOrders.getCreatetime());
		    		workOrders.setOrgi(tempWorkOrders.getOrgi());
		    		workOrders.setOrgan(tempWorkOrders.getOrgan());
		    		workOrders.setOrderno(tempWorkOrders.getOrderno());
		    		workOrders.setTitle(tempWorkOrders.getTitle());
		    		
		    		if(!StringUtils.isBlank(workOrders.getAccuser())){
		    			workOrders.setAssigned(true);
		    		}else{
		    			workOrders.setAssigned(false);
		    		}
		    		
		    		/**
	        		 * 数据变更记录
	        		 */
		    		DataEvent dataEvent = new DataEvent();
		    		if(tempWorkOrders.getAccuser()!=null && tempWorkOrders.getAccuser().equals(workOrders.getAccuser())){
	            		dataEvent.setEventtype(UKDataContext.WorkOrdersEventType.ACCEPTUSER.toString());
	            	}
	        		dataEvent.setDataid(workOrders.getId());
	    			dataEvent.setCreater(super.getUser(request).getId());
	    			dataEvent.setOrgi(super.getOrgi(request));
	    			dataEvent.setModifyid(UKTools.genID());
	    			dataEvent.setCreatetime(new Date());
	            	dataEvent.setCreatetime(new Date());
	            	dataEvent.setName("workorders");
	            	dataEventRes.save(dataEvent) ;
	            	if(files!=null && files.length > 0){
	            		UKTools.processAttachmentFile(files, attachementRes , path, super.getUser(request) , super.getOrgi(request), workOrders, request, comment.getId(), workOrders.getId());
	            	}
	            	
		    		Date modifytime = new Date();
		    		for(PropertiesEvent event : events){
		    			event.setDataid(workOrders.getId());
		    			event.setCreater(super.getUser(request).getId());
		    			event.setOrgi(super.getOrgi(request));
		    			event.setModifyid(dataEvent.getId());
		    			event.setCreatetime(modifytime);
		    			if(event.getField().equals("content") && !StringUtils.isBlank(comment.getContent())){
		    				String text = Jsoup.parse(comment.getContent()).text() ;
		    				if(text.length() > 200){
		    					event.setNewvalue(text.substring(0, 200));
		    				}else if(text.length() > 0){
		    					event.setNewvalue(text);
		    				}
		    			}
		    		}
		    		propertiesEventRes.save(events) ;
		    	}
	    	}else{
				result.setStatus(RestResultType.WORKORDERS_NOTEXIST);
			}
		}else{
			result.setStatus(RestResultType.WORKORDERS_NOTEXIST);
		}        
		return new ResponseEntity<>(result, HttpStatus.OK);
    }
}